$(function () {
    "use strict";

    $("#wrapped").validate({
        errorClass: "error",
        errorPlacement: function (error, element) { },
        onkeyup: function (element) {
            $(element).valid();
        }
    });

    $('#countries').msDropdown();
    $('#gender').msDropdown();
    $('#title').msDropdown();

    $('#username').focusout(function () {
        $("#username").css("outline", "");
    });

    $('#username').keyup(function () {
        console.log("here");
        var username = $(this).val();

        $.ajax({
            type: "GET",
            url: "http://uclwebservicetest.cloudapp.net/Services/users.svc/users/checkusername/" + username,
            contentType: "application/json; charset=utf-8",
            global: false,
            async: false,
            success: function (response) {
                /// Check if username exists or not
                if (response) {
                    $("#username").css("outline", "3px solid rgb(235, 46, 46)");
                    $("#username").css("margin-left", "3px");
                    $("#username").css("margin-top", "3px");
                } else {
              
                    $("#username").css("outline", "3px solid rgb(150, 191, 1)");
                    $("#username").css("margin-left", "3px");
                    $("#username").css("margin-top", "3px");
                }
            }
        });
    });

    $("#wizard-1").find('.progress').fadeIn();

    $('#with-progress').click(function () {
        var show_progress = $('#with-progress:checked').val();
    });

    $("#wizard-1").wizard({
        animations: {
            show: {
                options: {
                    duration: 500
                },
                properties: {
                    opacity: "show"
                }
            }
        },
        stepsWrapper: "#wrapped",
        submit: ".submit",
        beforeSelect: function (event, state) {
            var inputs = $(this).wizard('state').step.find(':input');
            return !inputs.length || !!inputs.valid();
        },
        afterBackward: function (event, state) {
            if (state.isFirstStep == true) {
                $('#navarrow').css({ 'display': 'none' });
                $('#txtSettings').html("Profile Settings");
            } else {
                $('#txtSettings').html("Account Settings");
            }
        },
        afterForward: function (event, state) {
            $('#navarrow').css({ 'display': 'inline' });
            if (state.isLastStep == true) {
                $('#txtSettings').html("Overview");
                $('#mandatoryfields').css({ 'display': 'none' });
            } else {
                $('#txtSettings').html("Account Settings");
            }
        },
        afterSelect: function (event, state) {
            // progress
            // manual percentComplete value (sometime its have some bugs)
            if (state.percentComplete == Infinity || isNaN(state.percentComplete) == true) {
                var total_steps = state.branchStepCount - 1,
                current_step = state.stepsActivated.length - 1;
                state.percentComplete = (current_step / total_steps) * 100;
            }
            $(this).find('.progress .bar').css("width", state.percentComplete + '%');

            // result
            if (state.isLastStep == true) {
                var fields = $('#wrapped').serializeArray();

                //$('#fname').text(fields[0].value)
                //$('#lname').text(fields[1].value)
                //$('#sgender').text(fields[2].value)


                var title = $('#title :selected').text();
                var firstname = $('#firstname').val();
                var lastname = $('#lastname').val();
                //var gender = $('#gender :selected').text();
                var country = $('#countries_title .ddlabel').text();
                var organisation = $('#organisation').val();
                var purpose = $('#purpose').val();
                var username = $('#username').val();
                var email = $('#email').val();
                var password = $('#password').val();

                $('#otitle').text(title);
                $('#ofirstname').text(firstname);
                $('#olastname').text(lastname);
               // $('#ogender').text(gender);

                if (country == "")
                    $('#ocountry').text("Not provided");
                else
                    $('#ocountry').text(country);

                if (organisation == "")
                    $('#oorganisation').text("Not provided");
                else
                    $('#oorganisation').text(organisation);

                if (purpose == "")
                    $('#opurpose').text("Not provided");
                else
                    $('#opurpose').text(purpose);

                $('#ousername').text(username);
                $('#oemail').text(email);
                $('#opassword').text(password);


            }
        }
    }).wizard('form').submit(function (event) {
        event.preventDefault();

        createDots();
        loadDots();

        var title = $('#title :selected').text();
        var firstname = $('#firstname').val();
        var lastname = $('#lastname').val();
        //var gender = $('#gender :selected').text();
        var country = $('#countries_title .ddlabel').text();
        var organisation = $('#organisation').val();
        var purpose = $('#purpose').val();
        var username = $('#username').val();
        var email = $('#email').val();
        var password = $('#password').val();


        var args = new Object();
        args.Country = country;
        args.EmailAddress = email;
        args.FirstName = firstname;
        args.LastName = lastname;
        //args.Sex = gender;
        args.Organization = organisation;
        args.Purpose = purpose;
        args.Title = title;
        args.Username = username;
        args.Password = password;

        setTimeout(function () {
            $.ajax({
                type: "POST",
                async: false,
                url: "http://uclwebservicetest.cloudapp.net/Services/users.svc/user",
                data: JSON.stringify(args),
                contentType: "application/json; charset=utf-8",
                beforeSend: function (xhr) {
                    // console.log("ARGS: %s", JSON.stringify(args));
                },
                success: function (response) {
                    console.log(response);
                    /// Create User Session and on success redirect to index page

                    $.ajax({
                        url: "scripts/Sessions.aspx",
                        global: false,
                        type: "GET",
                        async: false,
                        data: {
                            Uri: response.href,
                            Country: response.response.Country,
                            EmailAddress: response.response.EmailAddress,
                            //Gender: response.response.Sex,
                            FirstName: response.response.FirstName,
                            LastName: response.response.LastName,
                            Organization: response.response.Organization,
                            Purpose: response.response.Purpose,
                            Title: response.response.Title,
                            Id: response.response.Id,
                            Username: response.response.Username
                        },
                        //contentType: "application/json; charset=utf-8",
                        success: function (response) {
                            //alert("Session Created");
                            console.log(response);

                            var current = window.location.href;
                            var pos = current.lastIndexOf('/');
                            var redirect = current.substring(0, pos) + "/index.aspx";

                            window.location.href = redirect;
                        }
                    });
                },
                error: function (jqXHR, textStatus, errorThrown) {
                    console.log(textStatus, errorThrown);
                    console.log("ARGS: %s", JSON.stringify(args));
                }
            });
        }, 2000);

    }).validate({
        errorPlacement: function (error, element) {
            if (element.is(':radio') || element.is(':checkbox')) {
                error.insertAfter(element.parent().next());
            } else {
                error.insertAfter(element);
            }
        }
    });

    function createDots() {
        for (var i = 1; i <= 7; i++) {
            var div = $('<div class="divDots">').addClass('dot').css('transition', 'right ' + (0.6 + i / 10).toFixed(1) + 's ease-out');
            div.css('top', '0');
            div.prependTo($('#widget_preview'));


        }
    }

    function loadDots() {
        var i = 0;
        animateDots();
        function animateDots() {
            setTimeout(function () {
                var dots = $('div.dot');

                if (dots.length) {
                    dots.toggleClass('open');
                }
                i++;
                if (i < 1) {
                    animateDots();
                } else {
                }
            }, 1300)
        }
    }
});